"use strict";
const co = require("co");
//const suiteApp = require("../apps/suite_app");
const bossApi = require("../lib/boss_api");
const tool = require("../utils/common");
//const suiteDao = require("../dao/suite_dao");
const suiteToOrgDao = require("../dao/suite_to_org_dao");
const checkParam = function(req) {
	console.log(JSON.stringify(req.body));
	if (!req.body.suiteKey ||
		!req.body.suiteSecret ||
		!req.body.domainId ||
		!req.body.orgId) {
		console.error("参数不全", req.body);
		throw new Error("e_params");
	}
};
/*
1，验证用户有效性
2, 获取永久码
3，换取accesstoken和api地址
*/
const getContactOfCustomer = function(req, res) {
	const client = tool.getResponseFunc(res);
	const ctx = {
		domainId: req.body.domainId,
		orgId: req.body.orgId
	};
	const suiteSecret = req.body.suiteSecret;
	const getPermanentCode = function(suiteToOrg) {
		if (!suiteToOrg.permanentCode) {
			console.error("没有永久码，开始去兑换");
			const param = Object.assign({
				suiteSecret
			}, ctx, suiteToOrg);
			return bossApi.getPermanentCode(param);
		} else {
			return Promise.resolve(suiteToOrg.permanentCode);
		}
	};
	co(function*() {
		checkParam(req);

		const suiteToOrg = yield suiteToOrgDao.getSuiteToOrgBySuiteKey.call(ctx, req.body.suiteKey);
		console.log("找到的购买关系是", suiteToOrg);
		if (!suiteToOrg || !suiteToOrg.suiteKey.suiteKey) {
			console.error("没有找到购买关系");
			throw new Error("e_not_buy");
		}
		const param = Object.assign({
			suiteKey: req.body.suiteKey,
			suiteSecret: req.body.suiteSecret,
			suiteTicket: suiteToOrg.suiteKey.suiteTicket,
			tempAuthCode: suiteToOrg.tempAuthCode,
			permanentCode: suiteToOrg.permanentCode
		}, ctx);
		const contact = yield bossApi.getContact(param, yield getPermanentCode(param));
		client.success(contact);

	}).catch(client.fail);

};


module.exports = {
	getContactOfCustomer
};
